<template>
  <div class="main">
    <div class="search">
      <el-form :inline="true" :model="search">
        <el-form-item>
          <el-button type="success" size="small" @click="resetReportForm(); dialogShow = true">添加</el-button>
        </el-form-item>
        <el-form-item label="用户姓名">
          <el-input v-model="search.adName" size="small" placeholder="用户名" clearable></el-input>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="search.adUserName" size="small" placeholder="用户名" clearable></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="search.adPhone" size="small" placeholder="联系电话" clearable></el-input>
        </el-form-item>
        <!--        <el-form-item label="备注">-->
        <!--          <el-input v-model="search.description" size="small" placeholder="备注" clearable></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item>
          <el-button type="info" size="small" @click="searchClick">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="list">
      <el-table
          :data="data"
          stripe
          style="width: 100%">
        <el-table-column prop="adName" label="用户姓名"></el-table-column>
        <el-table-column prop="adUserName" label="用户名"></el-table-column>
        <el-table-column prop="adPhone" label="联系电话"></el-table-column>
        <el-table-column prop="adStatus" label="状态">
          <template slot-scope="scope">
            {{ scope.row.adStatus == '1' ? '启用' : '禁用' }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="备注" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="170px">
          <template slot-scope="scope">
            <el-button type="primary" @click="productInfoForm = {...scope.row}; dialogShow = true">编辑</el-button>
            <el-button type="danger" @click="del(scope.row.adId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="sizeChange"
          @current-change="currentChange"
          :current-page="pageNo"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <el-dialog
        :title="productInfoForm.id ? '添加' : '修改'"
        :visible.sync="dialogShow"
        width="600px"
        fullscreen
        @close="dialogClose"
    >
      <el-form ref="form" :model="productInfoForm" label-width="100px" :rules="rules">
        <el-row>
          <el-col :span="8">
            <el-form-item prop="productName" label="样品名称">
              <el-input type="text" placeholder="请输入样品名称" v-model="productInfoForm.productName"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="model" label="样品型号">
              <el-input type="text" placeholder="请输入样品型号" v-model="productInfoForm.model"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="sampleNum" label="涵盖机型">
              <el-input type="text" placeholder="请输入涵盖机型（或同单元机型）" v-model="productInfoForm.coveredModels"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="manufacturer" label="生产者">
              <el-input type="text" placeholder="请输入生产者" v-model="productInfoForm.manufacturer"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="manufacturerAddress" label="注册地址">
              <el-input type="text" placeholder="请输入注册地址" v-model="productInfoForm.manufacturerAddress"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="manufacturerPhone" label="电话">
              <el-input type="text" placeholder="请输入电话" v-model="productInfoForm.manufacturerPhone"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="manufacturerFax" label="传真">
              <el-input type="text" placeholder="请输入传真" v-model="productInfoForm.manufacturerFax"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="manufacturerContact" label="联系人">
              <el-input type="text" placeholder="请输入联系人" v-model="productInfoForm.manufacturerContact"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="manufacturerZipcode" label="邮政编码">
              <el-input type="text" placeholder="请输入邮政编码" v-model="productInfoForm.manufacturerZipcode"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="factory" label="生产厂">
              <el-input type="text" placeholder="请输入生产厂" v-model="productInfoForm.factory"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="factoryAddress" label="注册地址">
              <el-input type="text" placeholder="请输入注册地址" v-model="productInfoForm.factoryAddress"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="factoryPhone" label="电话">
              <el-input type="text" placeholder="请输入电话" v-model="productInfoForm.factoryPhone"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="factoryFax" label="传真">
              <el-input type="text" placeholder="请输入传真" v-model="productInfoForm.factoryFax"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="factoryContact" label="联系人">
              <el-input type="text" placeholder="请输入联系人" v-model="productInfoForm.factoryContact"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="factoryZipcode" label="邮政编码">
              <el-input type="text" placeholder="请输入邮政编码" v-model="productInfoForm.factoryZipcode"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="judgmentBasis" label="鉴定依据">
              <el-input type="text" placeholder="请输入鉴定依据" v-model="productInfoForm.judgmentBasis"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="judgmentConclusion" label="鉴定结论">
              <div style="border: 1px solid #ccc; max-height: 300px;">
                <toolbar
                    style="border-bottom: 1px solid #ccc"
                    :editor="editor"
                    :defaultConfig="toolbarConfig"
                    mode="default"
                />
                <editor
                    style="height: 800px; overflow-y: hidden;"
                    v-model="productInfoForm.judgmentConclusion"
                    :defaultConfig="editorConfig"
                    mode="default"
                    @onCreated="onCreated"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="registeredAddressSample" label="备注">
              <el-input type="textarea" placeholder="请输入备注" v-model="productInfoForm.remark"/>
            </el-form-item>
          </el-col>
        </el-row>
        <br/>
        <el-row>
          <el-col :span="8">
            <el-form-item prop="pictureProductName" label="产品照片">
              <el-upload
                  class="avatar-uploader"
                  style="border: 1px solid #d9d9d9; width: 100px; height: 100px"
                  :action="baseUrl + '/reportApproval/report/fileUplod'"
                  :headers="{'Authorization': getToken()}"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                <img v-if="productInfoForm.pictureProductName" :src="productInfoForm.pictureProductName" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" style="margin-left: 40px; margin-top: 40px;"></i>
              </el-upload>
              <!--              <el-input type="text" placeholder="请输入样品照片" v-model="productInfoForm.pictureProductName"/>-->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="pictureModel" label="产品特征">
              <el-input type="text" placeholder="请输入产品特征" v-model="productInfoForm.pictureModel"/>
            </el-form-item>
          </el-col>
        </el-row>
        <br/>
        <el-row>
          <el-col :span="24">
            <span style="margin-left: 30px; font-weight: bold; font-size: 20px;">
              一致性检查（产品样机技术规格）
            </span>
          </el-col>
        </el-row>
        <el-row v-for="(item, index) in productInfoForm.proTecSpecVo" :key="index">
          <el-col :span="4">
            <el-form-item label="序号">
              {{index + 1}}
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item prop="projectName" label="项目">
              <el-input type="text" placeholder="请输入项目" v-model="item.projectName"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item prop="unit" label="单位">
              <el-input type="text" placeholder="请输入单位" v-model="item.unit"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="designValue" label="设计值">
              <el-input type="text" placeholder="请输入设计值" v-model="item.designValue"/>
            </el-form-item>
          </el-col>
          <el-col :offset="10" :span="4">
            <el-form-item>
              <el-button type="primary" v-if="productInfoForm.proTecSpecVo.length === index + 1" circle icon="el-icon-plus" @click="addItem(productInfoForm.proTecSpecVo)"></el-button>
              <el-button v-if="index > 0" type="danger" circle icon="el-icon-minus" @click="delItem(productInfoForm.proTecSpecVo, index)"></el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item prop="remarks" label="备注">
              <el-input type="text" placeholder="请输入设计值" v-model="productInfoForm.remarks"/>
            </el-form-item>
          </el-col>
        </el-row>
        <br/>
        <el-row>
          <el-col :span="24">
            <span style="margin-left: 30px; font-weight: bold; font-size: 20px;">
              涵盖机型（或同单元机型）样机技术规格
            </span>
          </el-col>
        </el-row>
        <el-row v-for="(item, index) in productInfoForm.proCoveredModelVo" :key="index">
          <el-col :span="4">
            <el-form-item label="序号">
              {{index + 1}}
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item prop="projectName" label="项目">
              <el-input type="text" placeholder="请输入项目" v-model="item.projectName"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item prop="unit" label="单位">
              <el-input type="text" placeholder="请输入单位" v-model="item.unit"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="designValue" label="设计值1">
              <el-input type="text" placeholder="请输入设计值1" v-model="item.coverOne"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item prop="designValue" label="设计值2">
              <el-input type="text" placeholder="请输入设计值2" v-model="item.coverTwo"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item prop="designValue" label="设计值3">
              <el-input type="text" placeholder="请输入设计值3" v-model="item.coverThree"/>
            </el-form-item>
          </el-col>

          <el-col :offset="10" :span="4">
            <el-form-item>
              <el-button type="primary" v-if="productInfoForm.proCoveredModelVo.length === index + 1" circle icon="el-icon-plus" @click="addItem(productInfoForm.proCoveredModelVo)"></el-button>
              <el-button v-if="index > 0" type="danger" circle icon="el-icon-minus" @click="delItem(productInfoForm.proCoveredModelVo, index)"></el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item prop="remarks" label="备注">
              <el-input type="text" placeholder="请输入设计值" v-model="productInfoForm.remarks"/>
            </el-form-item>
          </el-col>
        </el-row>
        <br/>

        <el-row>
          <el-col :span="8">
            <el-form-item prop="reportWriter" label="报告编写人">
              <el-input type="text" placeholder="请输入报告编写人" v-model="productInfoForm.reportWriter"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="reportWriter" label="报告编写日期">
              <el-date-picker
                  v-model="productInfoForm.reportDate"
                  type="date"
                  format="yyyy-MM-dd"
                  placeholder="选择报告编写日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <!--        <el-form-item prop="description" label="备注">-->
        <!--          <el-input type="textarea" placeholder="请输入备注" v-model="productInfoForm.description"/>-->
        <!--        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" @click="submit">保存</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {httpBaseUrl} from "../util/globa";
import '@wangeditor/editor/dist/css/style.css'
import {Editor, Toolbar} from "@wangeditor/editor-for-vue";
import {getToken} from "../util/auth";

export default {
  name: "Admin",
  components: {Toolbar, Editor},
  data() {
    return {
      editor: null,
      toolbarConfig: {
      },
      editorConfig: {
        placeholder: '请输入内容...'
      },
      search: {},
      dialogShow: false,
      productInfoForm: {
        reportConditionVo: [{}],
        reportCheckResultVo: [{}],
        reportSampleSonsResultsVo: [{}],
        reportSampleSafetyResultsVo: [{}],
        reportConsResultsVo: [{}],
        reportSampleSuitResultsVo: [{}],
        reportReliabilityResultVo: [{}],
        reportReliabilityConsResultVo: [{}],
        proTecSpecVo: [{}],
        proCoveredModelVo: [{}]
      },
      data: [],
      pageNo: 1,
      pageSize: 10,
      total: 0,
      rules: {
        adName: [
          {
            required: true,
            type: 'string',
            message: '用户姓名不能为空',
            trigger: 'blur'
          }
        ],
        adUsername: [
          {
            required: true,
            type: 'string',
            message: '用户名不能为空',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 30,
            message: '用户名长度在3-30位之间',
            trigger: 'blur'
          },
          {
            pattern: /^[0-9A-Za-z_]{3,30}$/,
            message: '用户名只能包含数字、字母、下划线',
            trigger: 'blur'
          },
          // {
          //   validator: (rule, val, cb) => {
          //     let url = `admin/repeat?username=${val}`
          //     if (this.productInfoForm.id) url += `&id=${this.productInfoForm.id}`
          //     this.$http.get(url).then(res => {
          //       if (res.code === 200) {
          //         if (res.data) {
          //           return cb(new Error('用户名已存在！'))
          //         }
          //         cb()
          //       }
          //     })
          //   },
          //   trigger: 'blur'
          // }
        ],
        adPassword: [
          {
            required: false,
            type: 'string',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 30,
            message: '密码长度在6-30位之间',
            trigger: 'blur'
          },
          {
            pattern: /^[a-zA-Z0-9-*/+.~!@#$%^&*()]{6,30}$/,
            message: '密码只能包含数字、字母、特殊字符',
            trigger: 'blur'
          }
        ],
        adPhone: [
          {
            required: true,
            type: 'string',
            message: '电话不能为空',
            trigger: 'blur'
          },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '电话号码格式不正确',
            trigger: 'blur'
          }
        ],
        description: [
          {
            min: 0,
            max: 800,
            message: '备注长度在3-800位之间',
            trigger: 'blur'
          }
        ]
      },
      baseUrl: httpBaseUrl
    }
  },
  mounted() {
    this.getData()
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      const uploadImage = this.editor.getMenuConfig('uploadImage')
      uploadImage.server = '/upload/image'
      uploadImage.fieldName = 'file'
      uploadImage.headers = {
        token: getToken()
      }
      uploadImage.maxFileSize = 10 * 1024 * 1024
      const uploadVideo = this.editor.getMenuConfig('uploadVideo')
      uploadVideo.server = '/upload/video'
      uploadVideo.fieldName = 'file'
      uploadVideo.headers = {
        token: getToken()
      }
      uploadVideo.maxFileSize = 500 * 1024 * 1024
    },
    handleAvatarSuccess(res, file) {
      console.log('======================================');
      console.log(res);
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      return isJPG;
    },
    getToken() {
      return `Bearer ${sessionStorage.getItem('token')}`;
    },
    addItem(array, value = {}) {
      array.push(value);
    },
    delItem(array, index) {
      array.splice(index, 1);
    },
    getData() {
      this.search.page = this.pageNo;
      this.search.limit = this.pageSize;
      this.$http.post(`/reportApproval/admin/list`, this.search).then(res => {
        if (res.code === 0) {
          this.pageSize = res.page.pageSize
          this.pageNo = res.page.currPage
          this.total = res.page.totalCount
          this.data = res.page.list
        }
      })
    },
    sizeChange(val) {
      this.pageNo = 1;
      this.pageSize = val;
      this.getData();
    },
    currentChange(val) {
      this.pageNo = val;
      this.getData();
    },
    searchClick() {
      this.pageNo = 1;
      this.getData()
    },
    resetReportForm() {
      this.productInfoForm = {
        reportConditionVo: [{}],
        reportCheckResultVo: [{}],
        reportSampleSonsResultsVo: [{}],
        reportSampleSafetyResultsVo: [{}],
        reportConsResultsVo: [{}],
        reportSampleSuitResultsVo: [{}],
        reportReliabilityResultVo: [{}],
        reportReliabilityConsResultVo: [{}],
        proTecSpecVo: [{}],
        proCoveredModelVo: [{
          cover: ['']
        }]
      }
    },
    dialogClose() {
      this.resetForm();
      this.$refs['form'].clearValidate()
    },
    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.productInfoForm.adId) {
            this.productInfoForm.adUpdated = null;
            this.productInfoForm.adCreated = null;
            this.$http.post(`/reportApproval/admin/update`, this.productInfoForm).then(res => {
              if(res.code === 0) {
                this.$Message.success(res.msg)
                this.getData()
                this.dialogShow = false
              }
            })
          } else {
            this.$http.post(`/reportApproval/admin/save`, this.productInfoForm).then(res => {
              if(res.code === 0) {
                this.$Message.success(res.msg)
                this.getData()
                this.dialogShow = false
              }
            })
          }
        }
      });
    },
    del(id) {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(id)
        this.$http.post(`/reportApproval/admin/delete`, [id]).then(res => {
          if (res.code === 0) {
            this.getData()
            this.$Message.success(res.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>

<style scoped>

</style>
